#include "./macroCommand.hpp"
#include <algorithm>

using namespace qbe::undoRedoT;

// 清除包含指针的容器，释放指针，最后清空容器
template <typename T>
void ContainerDeleter(T& Container) {
  for (typename T::iterator iter = Container.begin(); iter != Container.end(); iter++) {
    delete (*iter);
  }
  Container.clear();
}

MacroCommand::MacroCommand() {}

// 析构时释放容器中命令
MacroCommand::~MacroCommand() {
  ContainerDeleter<std::vector<BaseCommand*>>(m_vecCommands);
}

// 执行所有命令，某一条若执行失败，则立即退出
bool MacroCommand::Execute() {
  for (unsigned int i = 0; i < m_vecCommands.size(); i++) {
    BaseCommand* pCommand = m_vecCommands[i];
    if (!pCommand->Execute()) {
      return false;
    }
  }
  return true;
}

// 取消执行命令，若一条执行失败，立即退出
bool MacroCommand::Unexecute() {
  for (unsigned int i = m_vecCommands.size(); i > 0; i--) {
    BaseCommand* pCommand = m_vecCommands[i - 1];
    if (!pCommand->Unexecute()) {
      return false;
    }
  }
  return true;
}

void MacroCommand::AddCommand(BaseCommand* pCommand) {
  if (pCommand) {
    m_vecCommands.push_back(pCommand);
  }
}

void MacroCommand::DeleteCommand(BaseCommand* pCommand) {
  if (pCommand) {
    m_vecCommands.erase(std::remove(m_vecCommands.begin(), m_vecCommands.end(), pCommand));
  }
}

bool MacroCommand::checkTag(std::string info) {
  bool child_res = false;
  for (auto& comm : m_vecCommands) {
    child_res = comm->checkTag(info);
    if (child_res) {
      return true;
    }
  }

  return BaseCommand::checkTag(info);
}